#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "rsa.c"


/*
 * 文件读取
 * 输入：txt文件，全局变量
 * 输出：读取的二维字符数组，全局变量
 */ 
void ReadText(char *path, char M[][2*MODULU_BYTES], int *number) {
	char buf[2*MODULU_BYTES+1];
	buf[2*MODULU_BYTES] = '\0';
	// char M[1000][234];
    FILE *fp;
    int len;

    if ((fp = fopen(path, "r")) == NULL) {
        perror("fail to read");
        exit(1);
    }

	int index = 0;
    while (fgets(buf, 2 * (MODULU_BYTES - 11) + 1, fp) != NULL) {
		len = strlen(buf);
		if (buf[len-1] == '\n') {
			len--;
		}
		if (len == 2*(MODULU_BYTES-11)) {
			strncat(M[index], buf, len);
			// printf("M[index] is: %s\n", M[index]);
			// printf("strlen(M[index]) is: %d\n", strlen(M[index]));
			index++;
		} else if (len % 2 != 0) {
			printf("ERROR: the number of character in the input file must be even!\n");
			exit(-1);
		}
		else {
			strncat(M[index], buf, len);
			// printf("M[index] is: %s\n", M[index]);
			// printf("strlen(M[index]) is: %d\n", strlen(M[index]));
			index++;
		}
		
		*number = index;
	}	

    fclose(fp);
    return;
}

int main() {


	char M[1000][2*MODULU_BYTES];
	int number = 0;
	ReadText("input.txt", M, &number);


	printf("==============================================Generate_Key===================================================\n");
	mpz_t e, d, N;
	mpz_inits(e, d, N, NULL);
	GenerateKey(e, d, N);

	gmp_printf("e: %Zx\n", e);
	gmp_printf("d: %Zx\n", d);
	gmp_printf("N: %Zx\n", N);

	printf("=========================================RSAES_PKCS1_V1_5_ENCRYPT============================================\n");

	char C[1000][2*MODULU_BYTES+1] = { '\0' };
	
	for (int i = 0; i < number; ++i) {
		RSAES_PKCS1_V1_5_ENCRYPT(N, e, (const unsigned char*)M[i], (unsigned char*)C[i]);

		printf("M[%d] is: %s\n", i, M[i]);
		printf("strlen(M[%d]) is: %d\n", i, strlen(M[i]));
	
		printf("C[%d] is: %s\n", i, C[i]);

		printf("strlen(C[%d]) is: %d\n", i, strlen(C[i]));
	}

	printf("==========================================RSAES_PKCS1_V1_5_DECRYPT===========================================\n");
	char M_de[1000][2*MODULU_BYTES+1] = { '\0' };

	for (int i = 0; i < number; ++i) {
		RSAES_PKCS1_V1_5_DECRYPT(N, d, (unsigned char*)C[i], M_de[i]);

		printf("M_de[%d] is: %s\n", i, M_de[i]);

		printf("strlen(M_de[%d]) is: %d\n", i, strlen((const char*)M_de[i]));

	}
}